package cn.example.vip.mall.user.service.impl;

import cn.example.vip.mall.user.entity.UserInfo;
import cn.example.vip.mall.user.mapper.UserInfoMapper;
import cn.example.vip.mall.user.service.UserInfoService;
import cn.example.vip.mall.user.util.JwtTokenUtils;
import cn.example.vip.mall.util.RespCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
	@Autowired
	private UserInfoMapper userInfoMapper;
	@Autowired
	private HttpServletRequest request;
	
	/**
	 * 用户注册
	 * @param userInfo
	 * @return
	 */
	@Transactional
	@Override
	public Integer userRegister(UserInfo userInfo) {
		// 检查注册信息是否充足
		if(userInfo.getUsername() == null || userInfo.getPassword() == null){
//			throw new RuntimeException("用户注册信息不足");
			return RespCode.ERROR.getCode();
		}
		
		// 查询用户是否存在
		QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("username", userInfo.getUsername());
		if(userInfoMapper.selectCount(queryWrapper) > 0){
//			throw new RuntimeException("用户已存在");
			return RespCode.SYSTEM_ERROR.getCode();
		}
		// 如果不存在则添加用户
		// 创建用户实例
		UserInfo user = new UserInfo();
		user.setUsername(userInfo.getUsername());
		user.setPassword(userInfo.getPassword());
		System.err.println(user);
		try {
			userInfoMapper.insert(user);
		}catch (Exception e){
			throw new RuntimeException("用户创建失败");
		}
		return RespCode.SUCCESS.getCode();
	}
	
	/**
	 * 用户登录
	 * @param userInfo
	 * @return
	 */
	@Override
	public Integer userLogin(HttpServletResponse response, UserInfo userInfo) {
		// 检查登录信息是否充足
		if(userInfo.getUsername() == null || userInfo.getPassword() == null){
			return RespCode.ERROR.getCode();
		}
		// 查询用户是否存在
		QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("username", userInfo.getUsername());
		List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper);
		if(userInfos.isEmpty()){
			return RespCode.SYSTEM_ERROR.getCode();
		}
		
		// 密码对比
		if(userInfo.getPassword().equals(userInfos.get(0).getPassword())){
			String token = JwtTokenUtils.sign(userInfo);
			response.addHeader("Access-Control-Expose-Headers", "token");	// 设置 headers放行
			response.addHeader("token", token);
			return RespCode.SUCCESS.getCode();
		}
		return RespCode.ERROR.getCode();
	}
}
